package com.qianfeng.android.baoman.util;


import org.apache.http.HttpConnection;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpEntityEnclosingRequestBase;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Set;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

/**
 * Created with IntelliJ IDEA
 * User:Maxiaoyu
 * Date:14-12-29
 * Email:731436452@qq.com
 */

/**
 * Http网络请求的工具类，包含了GET,POST,PUT,DELETE 这四中方法的请求方法的支持
 */
public class HttpTool {

    /**
     * 执行GET请求
     *
     * @param url 请求网址
     * @return 返回字节数组 网络数据
     */
    public static byte[] get(String url) {
        byte[] ret = null;
        if (url != null) {
            HttpGet request = new HttpGet(url);
            ret = processEntityRequest(request);
        }
        return ret;
    }

    /**
     * 执行DELETE请求
     *
     * @param url
     * @return
     */
    public static byte[] delete(String url) {
        byte[] ret = null;
        if (url != null) {
            HttpDelete request = new HttpDelete(url);
            ret = processEntityRequest(request);
        }
        return ret;
    }

    private static byte[] processEntityRequest(HttpRequestBase request) {
        byte[] ret = null;
        if (request != null) {
            HttpClient client = new DefaultHttpClient();
            HttpParams httpParams = client.getParams();
//            HttpConnectionParams.setConnectionTimeout(httpParams, 5000);
//            HttpConnectionParams.setSoTimeout(httpParams, 5000);
            try {
                HttpResponse response = client.execute(request);
                int statusCode = response.getStatusLine().getStatusCode();
                if (statusCode == HttpURLConnection.HTTP_OK) {
                    HttpEntity entity = response.getEntity();
                    ret = EntityUtils.toByteArray(entity);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return ret;
    }

    /**
     * 执行post请求 <br/>
     * POST 请求提交数据，提交数据的方式
     * 本方法采用提交key=value&key=value的方式
     * 这种数据格式就是网页中，from表单提交的数据格式
     *
     * @param params HashMap包含的参数，也就是key=value 的集合
     * @param url    请求的网址
     * @return
     */
    public static byte[] post(String url, HashMap<String, String> params) {
        return post(url, params, "UTF-8");
    }

    public static byte[] post(String url, HashMap<String, String> params, String encoding) {
        byte[] ret = null;
        if (url != null) {
            HttpPost request = new HttpPost(url);
            ret = processEntityRequest(request, params, encoding);
        }
        return ret;
    }

    /**
     * put 请求
     *
     * @param url
     * @param params
     * @param encoding
     * @return
     */
    public static byte[] put(String url, HashMap<String, String> params, String encoding) {
        byte[] ret = null;
        if (url != null) {
            HttpPut request = new HttpPut(url);
            ret = processEntityRequest(request, params, encoding);
        }
        return ret;
    }

    /**
     * 本方法实现了ＰＯＳＴ请求与PUT请求，发送key=value 形式的通用代码
     *
     * @param request
     * @param params
     * @param encoding
     * @return
     */
    private static byte[] processEntityRequest(HttpEntityEnclosingRequestBase request,
                                               HashMap<String, String> params, String encoding) {
        byte[] ret = null;
        if (request != null) {
            if (params != null) {
                try {
                    //用于设置提交的数据
                    //对于key=value&key=value的形式，需要使用UrlEncodedFormEntity
                    LinkedList<NameValuePair> parameters = new LinkedList<NameValuePair>();

                    //TODO　添加参数
                    Set<String> keySet = params.keySet();
                    for (String key : keySet) {
                        String value = params.get(key);
                        parameters.add(new BasicNameValuePair(key, value));
                    }
                    //将parameters中的 key--value 通过UrlEncodedFormEntity进行组合形成key=value的形式，
                    //这种形式是服务器标准数据提交的格式
                    //必须使用两个参数的构造方法，防止乱码
                    if (encoding == null) {
                        encoding = "UTF-8";
                    }
                    UrlEncodedFormEntity entity = new UrlEncodedFormEntity(parameters, encoding);
                    request.setEntity(entity);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            HttpClient client = new DefaultHttpClient();
            HttpParams httpParams = client.getParams();
            HttpConnectionParams.setConnectionTimeout(httpParams, 3000);
            HttpConnectionParams.setSoTimeout(httpParams, 3000);
            try {
                HttpResponse response = client.execute(request);
                int code = response.getStatusLine().getStatusCode();
                if (code == 200) {
                    HttpEntity entity = response.getEntity();
                    ret = EntityUtils.toByteArray(entity);

                }
                if (code == 201) {
                    HttpEntity entity = response.getEntity();
//                    ret = EntityUtils.toByteArray(entity);
                    /*String s = EntityUtils.toString(entity);
                    System.out.println("s = " + s);*/
                    ret = EntityUtils.toByteArray(entity);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return ret;
    }

    /**
     * 带线程池的访问网络
     *
     * @param path
     * @return
     */
    public static byte[] getContent(final String path) {
        byte[] bt = null;
        ExecutorService service = Executors.newSingleThreadExecutor();
        Future<byte[]> submit = service.submit(new Callable<byte[]>() {
            @Override
            public byte[] call() throws Exception {
                byte[] buf;
                HttpClient httpClient = new DefaultHttpClient();
                HttpParams params = httpClient.getParams();
                HttpConnectionParams.setConnectionTimeout(params, 3000);
                HttpConnectionParams.setSoTimeout(params, 3000);
                HttpResponse hResponse;

                HttpGet hGet = new HttpGet(path);
                hResponse = httpClient.execute(hGet);

                if (hResponse.getStatusLine().getStatusCode() == 200) {
                    HttpEntity entity = hResponse.getEntity();
                    buf = EntityUtils.toByteArray(entity);
                    String ret = new String(buf);
                    System.out.println("ret = " + ret);
                    return buf;
                }
                return null;
            }
        });
        try {
            bt = submit.get();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
        service.shutdown();
        return bt;
    }


}

